import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import '../../../config/kq_global.dart';
import '../../../resources/images.dart';
import '../../../resources/kq_theme_colors.dart';
import '../../../resources/l10n/kq_intl.dart';
import '../../../theme/kq_theme_manager.dart';
import '../../button/kq_icon_button.dart';

///组选择器
class KqOptionsBottomSheet<T> extends StatefulWidget {
  ///标题
  final String title;

  /// 数据源
  final List<T> items;

  ///列
  final int columns;

  ///宽高比例
  final double? childAspectRatio;

  ///横向间距 默认：10.r
  final double? crossAxisSpacing;

  ///纵向间距
  final double? mainAxisSpacing;

  ///界面展示的高度 以行数为基准计算
  final int maxRows;

  /// 对话框背景颜色
  final Color? bgColor;

  ///标题样式，默认大小16，颜色262626
  final TextStyle? titleStyle;

  ///是否展示底部的全选 确定按钮
  final bool isShowBottom;

  ///选中的数据
  final String? chooseIds;

  ///底部自定义
  final Widget Function()? customBottomBuilder;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? nameConvert;

  /// 转换 T -> String 转换
  final String Function(int index, T item)? idConvert;

  /// 转换 T -> bool 转换  禁用相关的
  final bool Function(int index, T item)? statusConvert;

  /// 多选回调
  final Function(List<T> chooses)? moreCallback;

  /// 单选回调
  final Function(T item)? singleCallback;

  const KqOptionsBottomSheet(
      {Key? key,
      required this.title,
      required this.items,
      this.columns = 3,
      this.childAspectRatio,
      this.crossAxisSpacing,
      this.mainAxisSpacing,
      this.maxRows = 4,
      this.bgColor,
      this.titleStyle,
      this.nameConvert,
      this.idConvert,
      this.statusConvert,
      this.isShowBottom = false,
      this.chooseIds,
      this.customBottomBuilder,
      this.moreCallback,
      this.singleCallback})
      : assert((moreCallback != null && !isShowBottom) ||
            (singleCallback != null && isShowBottom)),
        super(key: key);

  @override
  State<KqOptionsBottomSheet> createState() => _KqOptionsBottomSheetState<T>();
}

class _KqOptionsBottomSheetState<T> extends State<KqOptionsBottomSheet<T>> {
  ///选择的
  List<T> _chooseItems = [];

  ///是否全选
  bool _allChoose = false;

  @override
  void initState() {
    if (widget.moreCallback != null) {
      //多选
      var list = widget.chooseIds?.split(',') ?? [];
      for (var i = 0; i < list.length; i++) {
        for (var j = 0; j < widget.items.length; j++) {
          String id = widget.idConvert?.call(j, widget.items[j]) ?? '';
          if (list[i] == id) {
            _chooseItems.add(widget.items[j]);
            break;
          }
        }
      }
    } else if (widget.singleCallback != null) {
      //单选
      for (var j = 0; j < widget.items.length; j++) {
        String? id = widget.idConvert?.call(j, widget.items[j]);
        if (widget.chooseIds == id) {
          _chooseItems.add(widget.items[j]);
          break;
        }
      }
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var padding = MediaQuery.of(context).viewInsets.bottom;

    double childAspectRatio = widget.childAspectRatio ?? 61 / 18;
    double crossAxisSpacing = widget.crossAxisSpacing ?? 8.r;
    // 小诸葛规范，最多显示6个，多余滚动
    double width =
        (context.width - 16.r * 2 - (widget.columns - 1) * crossAxisSpacing) /
            widget.columns;
    var maxHeight = widget.maxRows * (width / childAspectRatio + 8.r);
    Widget result = Stack(
      children: [
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(vertical: 16.r),
          child: Text(
            widget.title,
            style: widget.titleStyle ??
                TextStyle(
                    fontSize: 16.sp,
                    color: KqThemeColors.text26,
                    fontWeight: FontWeight.w600),
          ),
        ),
        Positioned(
          right: 0,
          top: 0,
          bottom: 0,
          child: KqIconButton(
            size: 46.r,
            onPressed: () => Navigator.pop(context),
            icon: Image.asset(
              Images.commonIcGuanbi,
              height: 14.r,
              width: 14.r,
              package: KqGlobal.packageName,
            ),
          ),
        )
      ],
    );

    List<Widget> children = [
      result,
      // if (widget.isTitleBottomLine) const KqDivider(),
      // if (widget.isTitleBottomLine) SizedBox(height: 14.r),
      LimitedBox(
        maxHeight: maxHeight,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.r),
          child: GridView(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: widget.columns,
              childAspectRatio: childAspectRatio,
              crossAxisSpacing: crossAxisSpacing,
              mainAxisSpacing: widget.mainAxisSpacing ?? 8.r,
            ),
            children: _buildBody(),
          ),
        ),
      ),
      SizedBox(height: 8.r),
      if (widget.customBottomBuilder != null)
        widget.customBottomBuilder!.call(),
      if (widget.isShowBottom) _buildBottom(),
      if (!widget.isShowBottom && widget.customBottomBuilder == null)
        SizedBox(
          height: KqScreenUtil().bottomBarHeight,
        )
    ];

    return Padding(
      padding: EdgeInsets.only(bottom: padding),
      child: Material(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8.r))),
          color: widget.bgColor ??
              KqThemeManager.instance.getConfig().dialogConfig.bgColor ??
              KqThemeColors.bgF5,
          child: ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(8.r)),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: children,
            ),
          )),
    );
  }

  _buildBody() {
    //默认显示更多的时候
    List<Widget> forms = [];
    for (var i = 0; i < widget.items.length; i++) {
      var item = widget.items[i];
      String title;
      if (widget.nameConvert != null) {
        title = widget.nameConvert!(i, item);
      } else {
        if (item is String) {
          title = item;
        } else if (item is Map) {
          title = item['title'];
        } else {
          title = '';
        }
      }
      Color titleColor = KqThemeColors.text26;
      Color bgColor = KqThemeColors.bgWhite;
      if (_chooseItems.contains(item)) {
        titleColor = KqThemeColors.textWhite;
        bgColor = KqThemeColors.bgBlue;
      }
      forms.add(KqInkWell(
          onTap: () {
            if (widget.moreCallback != null) {
              //多选
              setState(() {
                if (_chooseItems.contains(item)) {
                  _chooseItems.remove(item);
                  _allChoose = false;
                } else {
                  _chooseItems.add(item);
                }
              });
            } else {
              //单选
              setState(() {
                if (_chooseItems.contains(item)) {
                  _chooseItems.remove(item);
                } else {
                  _chooseItems = [item];
                }
              });
              if (widget.singleCallback != null) {
                widget.singleCallback!.call(item);
              }
            }
          },
          verticalPadding: 2.r,
          horizontalPadding: 6.r,
          radius: 2.r,
          backgroundColor: bgColor,
          child: Container(
            alignment: Alignment.center,
            child: Text(
              title,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: titleColor,
                  fontSize: 12.sp,
                  height: 1.1,
                  leadingDistribution: TextLeadingDistribution.even),
            ),
          )));
    }

    return forms;
  }

  _buildBottom() {
    return Container(
      color: KqThemeColors.bgWhite,
      padding: EdgeInsets.only(
          top: 8.r, bottom: 8.r + KqScreenUtil().bottomBarHeight),
      child: Row(
        children: [
          LimitedBox(
            maxWidth: 90.r,
            child: SizedBox(
              height: 48.r,
              child: KqInkWell(
                  onTap: () {
                    if (_allChoose) {
                      //全不选
                      _chooseItems = [];
                      _allChoose = false;
                    } else {
                      //全选
                      bool status = true;
                      List<T> list = [];
                      for (var i = 0; i < widget.items.length; i++) {
                        if (widget.statusConvert != null) {
                          status = widget.statusConvert!(i, widget.items[i]);
                        }
                        if (status) {
                          list.add(widget.items[i]);
                        }
                      }
                      _chooseItems = list;
                      _allChoose = true;
                    }
                    setState(() {});
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Image.asset(
                        _allChoose
                            ? Images.commonIcChoice16CSel
                            : Images.commonIcChoice16Nor,
                        width: 16.r,
                        height: 16.r,
                        package: KqGlobal.packageName,
                      ),
                      SizedBox(width: 4.r),
                      Text(
                        KqIntl.currentResource.selectAll,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: KqThemeColors.text26, fontSize: 14.sp),
                      ),
                    ],
                  )),
            ),
          ),
          Expanded(
              child: Container(
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.r)),
            child: KqInkWell(
                onTap: () {
                  //确定
                  if (widget.moreCallback != null) {
                    widget.moreCallback!.call(_chooseItems);
                  }
                },
                backgroundColor: KqThemeColors.textBlue,
                child: Container(
                  height: 48.r,
                  alignment: Alignment.center,
                  child: Text(
                    KqIntl.currentResource.ok,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                  ),
                )),
          )),
          SizedBox(width: 16.r),
        ],
      ),
    );
  }
}
